package com.ciaojian.client.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciaojian.core.mapper.MemberDiscountMapper;
import com.ciaojian.core.model.Member;
import com.ciaojian.core.model.MemberDiscount;
import com.ciaojian.core.service.MemberDiscountService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @author Atlakyn
 */
@Service
public class MemberDiscountServiceImpl extends MemberDiscountService<MemberDiscountMapper, MemberDiscount> {

    /**
     * 用户购买会员获得首/多单优惠
     *
     * @param memberId 会员卡 id
     * @param userId   用户 id
     */
    public void addMemberDiscount(Integer memberId, Integer userId) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "discount_amount", "discount_count");
        queryWrapper.eq("id", memberId);
        Member dMember = new Member().selectOne(queryWrapper);
        // 如果 dMember 为空
        // 或 discountAmount(优惠数额) 为 null/0
        // 或 discountCount(优惠次数) 为 0
        // 则表示不优惠,退出方法
        if (dMember == null
                || dMember.getDiscountAmount() == null
                || dMember.getDiscountAmount().compareTo(BigDecimal.ONE) == 0
                || dMember.getDiscountCount() == 0) {
            return;
        }

        // 用户购买会员卡获得会员减免优惠,次数为后台设置的次数
        MemberDiscount memberDiscount;
        for (Integer i = 0; i < dMember.getDiscountCount(); i++) {
            memberDiscount = new MemberDiscount();
            memberDiscount.setAmount(dMember.getDiscountAmount());
            memberDiscount.setMemberId(dMember.getId());
            memberDiscount.setUserId(userId);
            memberDiscount.setCreateTime(System.currentTimeMillis());
            memberDiscount.insert();
        }
    }
}
